package com.yanqu.road.dao.impl.channelcenter;

import com.yanqu.road.dao.cache.SqlCacheParam;
import com.yanqu.road.dao.impl.TempNoPoolCacheDao;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.TimeHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 跨地区活动
 */
public class TempChannelActivityDaoImpl extends TempNoPoolCacheDao {

    public TempChannelActivityDaoImpl(String dbParam) {
        super(dbParam);
    }

    // ========================= activityInfo ==============================

    /**
     * 活动信息
     */
    public Map<Integer, ActivityInfo> getAllActivityInfoMap(long serverId, int channelActivityTimeZone) {

        String sql = "select * from t_n_activity_main where serverList like ?";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        sqlCacheParam.addParam(String.class, "%" + serverId + "%");
        sqlCacheParam.addOtherParam(channelActivityTimeZone);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return new ConcurrentHashMap<>((Map<Integer, ActivityInfo>) cacheResult);
        }

        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, ActivityInfo> dataMap = new ConcurrentHashMap<>();
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityInfo data = initActivityInfo(rs, channelActivityTimeZone);
                dataMap.put(data.getActivityId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, dataMap);
        return dataMap;
    }

    private ActivityInfo initActivityInfo(ResultSet rs, int channelActivityTimeZone) throws SQLException {
        ActivityInfo data = new ActivityInfo();
        data.setActivityId(rs.getInt("activityId"));
        data.setActivityName(rs.getString("activityName"));
        data.setActivityDesc(rs.getString("activityDesc"));
        data.setType(rs.getInt("type"));
        data.setChildType(rs.getInt("childType"));
        data.setBeginShowTime(rs.getTimestamp("beginShowTime").getTime() / 1000);
        data.setEndShowTime(rs.getTimestamp("endShowTime").getTime() / 1000);
        data.setBeginTime(rs.getTimestamp("beginTime").getTime() / 1000);
        data.setEndTime(rs.getTimestamp("endTime").getTime() / 1000);
        data.setIcon(rs.getString("icon"));
        data.setOrder(rs.getInt("order"));
        data.setParam1(rs.getString("param1"));
        data.setParam2(rs.getString("param2"));
        data.setParam3(rs.getString("param3"));
        data.setParam4(rs.getString("param4"));
        data.setParam5(rs.getString("param5"));
        data.setParam6(rs.getString("param6"));
        data.setUnionGroup(rs.getString("unionGroup"));
        data.setServerListStr(rs.getString("serverList"));
        data.setServerIdList(StringUtils.stringToLongList(data.getServerListStr(), ","));
        data.setServerListStr2(rs.getString("serverList2"));
        data.setCrossId(rs.getLong("crossServerId"));

        // 转化时区
        data.timeZoneChange(channelActivityTimeZone);

        return data;
    }

    /**
     * 是否是跨地区活动
     */
    public boolean isCrossChannelActivity(int activityId) {

        String sql = "select count(*) as num from t_n_activity_main where activityId=?";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        sqlCacheParam.addParam(Integer.class, activityId);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (boolean) cacheResult;
        }

        boolean result = false;
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            if (rs.next()) {
                int num = rs.getInt("num");
                if (num > 0) {
                    result = true;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, result);
        return result;
    }

    /**
     * 获取未结束的跨地区活动ID
     */
    public List<Integer> getNoEndCrossChannelActivityId(int channelActivityTimeZone) {

        long now = System.currentTimeMillis();
        long channelCenterNow = LocalDateTimeHelper.convertTimeZone(now, channelActivityTimeZone, false);
        SimpleDateFormat sdf = TimeHelper.getSimpleDateFormat(DateHelper.YMDHMS);
        String curTime = sdf.format(channelCenterNow);

        String sql = "select activityId from t_n_activity_main where endShowTime>?";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        sqlCacheParam.addParam(String.class, curTime);
        sqlCacheParam.addOtherParam(channelActivityTimeZone);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (List<Integer>) cacheResult;
        }

        ResultSet rs = null;
        CallableStatement call = null;
        List<Integer> idList = new ArrayList<>();
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                int activityId = rs.getInt("activityId");
                idList.add(activityId);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, idList);
        return idList;
    }

    /**
     * 根据活动ID获取活动信息
     */
    public ActivityInfo getActivityInfoById(int activityId, int channelActivityTimeZone) {

        String sql = "select * from t_n_activity_main where activityId = ?";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        sqlCacheParam.addParam(Integer.class, activityId);
        sqlCacheParam.addOtherParam(channelActivityTimeZone);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (ActivityInfo) cacheResult;
        }

        ActivityInfo info = null;
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            if (rs.next()) {
                info = initActivityInfo(rs, channelActivityTimeZone);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, info);
        return info;
    }

    /**
     * 根据大小类型获取全部活动
     */
    public Map<Integer, ActivityInfo> getOpeningActivityInfoByActivityType(int channelActivityTimeZone,int type, int childType) {

        long now = System.currentTimeMillis();
        long channelCenterNow = LocalDateTimeHelper.convertTimeZone(now, channelActivityTimeZone, false);
        SimpleDateFormat sdf = TimeHelper.getSimpleDateFormat(DateHelper.YMDHMS);
        String curTime = sdf.format(channelCenterNow);

        String sql = "select * from t_n_activity_main where endShowTime>? and type=? and childType=?";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        sqlCacheParam.addParam(String.class, curTime);
        sqlCacheParam.addParam(Integer.class, type);
        sqlCacheParam.addParam(Integer.class, childType);
        sqlCacheParam.addOtherParam(channelActivityTimeZone);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (Map<Integer, ActivityInfo>) cacheResult;
        }

        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, ActivityInfo> infoMap = new HashMap<>();
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityInfo info = initActivityInfo(rs, channelActivityTimeZone);
                infoMap.put(info.getActivityId(), info);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, infoMap);
        return infoMap;
    }




    // ========================= condition ==============================

    public List<ActivityConditionInfo> getActivityConditionInfoList(int activityId, int conditionType) {

        String sql = "select * from t_n_activity_condition where activityId=? and `type`=?";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        sqlCacheParam.addParam(Integer.class, activityId);
        sqlCacheParam.addParam(Integer.class, conditionType);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (List<ActivityConditionInfo>) cacheResult;
        }

        List<ActivityConditionInfo> infoList = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityConditionInfo data = initActivityConditionInfo(rs);
                infoList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, infoList);
        return infoList;
    }

    /**
     * 活动condition
     */
    public Map<Integer, List<ActivityConditionInfo>> getActivityConditionInfoMap(List<Integer> activityIdList) {
        if (activityIdList == null || activityIdList.size() <= 0) {
            return new ConcurrentHashMap<>();
        }

        String sql = "select * from t_n_activity_condition where activityId in(" + StringUtils.listToString(activityIdList, ",") + ")";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (Map<Integer, List<ActivityConditionInfo>>) cacheResult;
        }

        Map<Integer, List<ActivityConditionInfo>> infoMap = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityConditionInfo data = initActivityConditionInfo(rs);
                if (!infoMap.containsKey(data.getActivityId())) {
                    infoMap.put(data.getActivityId(), new ArrayList<>());
                }
                infoMap.get(data.getActivityId()).add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, infoMap);
        return infoMap;
    }

    private ActivityConditionInfo initActivityConditionInfo(ResultSet rs) throws SQLException {
        ActivityConditionInfo data = new ActivityConditionInfo();
        data.setConditionId(rs.getInt("id"));
        data.setActivityId(rs.getInt("activityId"));
        data.setTitle(rs.getString("title"));
        data.setDesc(rs.getString("desc"));
        data.setType(rs.getInt("type"));
        data.setRewardStr(rs.getString("rewards"));
        data.setParamStr(rs.getString("params"));
        data.setReward(PropertyHelper.parseStringToProperty(data.getRewardStr()));
        data.setParamList(StringUtils.stringToBigIntegerList(data.getParamStr(), "\\|"));
        String value = rs.getString("extendParam");
        if (!StringUtils.isNullOrEmpty(value)) {
            data.setExtendParam(value);
        }
        //职位奖励 会长奖励|副会长奖励|精英奖励
        data.setPositionRewardStr(rs.getString("masterRewards"));
        List<String> positionStrList = StringUtils.stringToStringList(data.getPositionRewardStr(), "\\|");
        if (positionStrList.size() > 0 && !StringUtils.isNullOrEmpty(positionStrList.get(0))) {
            data.setMasterReward(PropertyHelper.parseStringToProperty(positionStrList.get(0)));
            data.setMasterRewardStr(positionStrList.get(0));
        }
        if (positionStrList.size() > 1 && !StringUtils.isNullOrEmpty(positionStrList.get(1))) {
            data.setDeputyMasterRewardStr(positionStrList.get(1));
        }
        if (positionStrList.size() > 2 && !StringUtils.isNullOrEmpty(positionStrList.get(2))) {
            data.setEliteRewardStr(positionStrList.get(2));
        }
        data.setActtype(rs.getString("acttype"));
        return data;
    }

    // ========================= mall ==============================

    /**
     * 活动商店
     */
    public Map<Integer, Map<Integer, MallInfo>> getActivityMallInfoMap(List<Integer> activityIdList) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Integer, MallInfo>> dataMap = new ConcurrentHashMap<>();
        if (null == activityIdList || activityIdList.size() <= 0) {
            return dataMap;
        }

        String sql = "select * from t_n_activity_mall where activityId in(" + StringUtils.listToString(activityIdList, ",") + ")";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (Map<Integer, Map<Integer, MallInfo>>) cacheResult;
        }

        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                MallInfo data = new MallInfo();
                data.setActivityId(rs.getInt("activityId"));
                data.setMallId(rs.getInt("id"));
                data.setRechargeId(rs.getInt("rechargeId"));
                data.setMallName(rs.getString("name"));
                data.setShopType(rs.getInt("shopType"));
                data.setCategory(rs.getInt("category"));
                data.setReward(rs.getString("reward"));
                data.setRewardProp(PropertyHelper.parseStringToProperty(data.getReward()));
                data.setPrice(rs.getString("price"));
                data.setPriceAdd(rs.getInt("priceAdd"));
                data.setFirstDouble(rs.getBoolean("isDouble"));
                data.setLimitBuyType(rs.getInt("buyLimitType"));
                data.setLimitBuyCount(rs.getInt("buyLimit"));
                data.setSort(rs.getInt("sort"));
                data.setReturnIngots(rs.getInt("returnIngots"));
                data.setParam(rs.getString("param"));
                data.setPointSign(rs.getString("pointSign"));
                data.setOldPrice(rs.getString("oldPrice"));
                data.setShow(rs.getBoolean("isShow"));
                data.setExtendParam(rs.getString("extendParam"));
                data.setVipLimit(rs.getInt("vipLimit"));

                String shopId = rs.getString("shopId");
                data.setShopId(shopId == null ? "" : shopId);
                data.setBuyLimitParam(rs.getString("buyLimitParam"));
                data.setActivityType(rs.getString("acttype"));
                data.setCanBuyParam(rs.getString("canBuyParam"));
                data.setChannelId(rs.getInt("channelId"));
                data.setMallMarkId(rs.getInt("mallMarkId"));
                if (!dataMap.containsKey(data.getActivityId())) {
                    dataMap.put(data.getActivityId(), new ConcurrentHashMap<>());
                }
                dataMap.get(data.getActivityId()).put(data.getMallId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, dataMap);
        return dataMap;
    }

    /**
     * 活动通用配置
     */
    public Map<Integer, Map<String, ActivityConfig>> getActivityConfigMap(List<Integer> activityIdList) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<String, ActivityConfig>> dataMap = new ConcurrentHashMap<>();
        if (null == activityIdList || activityIdList.size() <= 0) {
            return dataMap;
        }

        String sql = "select * from t_n_activity_config where activityId in(" + StringUtils.listToString(activityIdList, ",") + ")";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        Object cacheResult = getCacheResult(sqlCacheParam);
        // 先读缓存
        if (cacheResult != null) {
            return (Map<Integer, Map<String, ActivityConfig>>) cacheResult;
        }

        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityConfig config = new ActivityConfig();
                config.setActivityId(rs.getInt("activityId"));
                config.setId(rs.getInt("id"));
                config.setParam(rs.getString("param"));
                config.setValue(rs.getString("value"));
                if (!dataMap.containsKey(config.getActivityId())) {
                    dataMap.put(config.getActivityId(), new ConcurrentHashMap<>());
                }
                dataMap.get(config.getActivityId()).put(config.getParam(), config);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, dataMap);
        return dataMap;
    }


    // ========================= switch ==============================

    /**
     * 活动开关
     */
    public Map<Integer, Map<Integer, Integer>> getActivitySwitchMap() {

        String sql = "select * from t_n_activity_switch";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        // 这个是开关，不是活动，不操作缓存
        /*
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (Map<Integer, Map<Integer, Integer>>) cacheResult;
        }*/

        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Integer, Integer>> mapMap = new ConcurrentHashMap<>();
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                int activityId = rs.getInt("activityId");
                int switchType = rs.getInt("switchType");
                int status = rs.getInt("status");
                if (!mapMap.containsKey(activityId)) {
                    mapMap.put(activityId, new ConcurrentHashMap<>());
                }
                mapMap.get(activityId).put(switchType, status);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 这个是开关，不是活动，不操作缓存
        /*
        addCacheResult(sqlCacheParam, mapMap);
        */
        return mapMap;
    }

    // ========================= 特殊SQL ==============================

    public Map<Integer, ActivityInfo> getRecentWasheActivityInfoMap(int channelId, int channelActivityTimeZone) {
        Timestamp todayZeroTime = new Timestamp(DateHelper.getTodayZeroTimeStamp()); // 时间用今天的时间，避免参数不同导致不读缓存
        ResultSet rs = null;
        CallableStatement call = null;

        String sql = "select * from t_n_activity_main where " +
                "endShowTime >= ?" +
                "and type in (?,?,?) " +
                "and param6 like ? ";
        SqlCacheParam sqlCacheParam = getCacheParam(sql);
        sqlCacheParam.addParam(Timestamp.class, todayZeroTime);
        sqlCacheParam.addParam(Integer.class, eActivityType.WasheActivity.getValue());
        sqlCacheParam.addParam(Integer.class, eActivityType.CrossPasture.getValue());
        sqlCacheParam.addParam(Integer.class, eActivityType.AreaWashePkActivity.getValue());
        sqlCacheParam.addParam(String.class, "%" + channelId + "%");
        sqlCacheParam.addOtherParam(channelActivityTimeZone);
        // 先读缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (Map<Integer, ActivityInfo>) cacheResult;
        }

        Map<Integer, ActivityInfo> infoMap = new ConcurrentHashMap<>();
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityInfo data = initActivityInfo(rs, channelActivityTimeZone);
                List<Integer> list = StringUtils.stringToIntegerList(data.getParam6(), ";");
                boolean anyMatch = list.stream().anyMatch(item -> item == channelId);
                if (anyMatch) {
                    infoMap.put(data.getActivityId(), data);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, infoMap);
        return infoMap;
    }

}
